package com.eascs.p2p.admin.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.inject.Inject;

import com.alibaba.dubbo.config.annotation.Service;
import com.eascs.app.dao.PageResult;
import com.eascs.common.util.DateUtils;
import com.eascs.p2p.admin.manager.IInvestObjectExtManager;
import com.eascs.p2p.admin.manager.IInvestObjectManager;
import com.eascs.p2p.admin.manager.IInvestRecordManager;
import com.eascs.p2p.admin.manager.IInvestorIncomeDetailManager;
import com.eascs.p2p.common.entity.InvestObjExtEntity;
import com.eascs.p2p.common.entity.InvestObjectEntity;
import com.eascs.p2p.common.entity.InvestorIncomeDetailEntity;
import com.eascs.p2p.common.entity.InvestorRecordEntity;
import com.eascs.p2p.common.entity.LoaneeRefundPlanEntity;
import com.eascs.p2p.common.service.IInvestObjectService;
import com.eascs.p2p.common.vo.InvestObjectVO;
import com.eascs.p2p.common.vo.ModelResult;
import com.eascs.p2p.investor.dao.InvestorDao;

@Service
public class InvestObjectServiceImpl implements IInvestObjectService {
	@Inject
	IInvestObjectManager investObjectManager;

	@Inject
	IInvestObjectExtManager investObjectExtManager;
	@Inject
	IInvestRecordManager investRecordManager;
	@Inject
	IInvestorIncomeDetailManager investorIncomeDetailManager;
	@Inject
	private InvestorDao investorDao;

	@Override
	public ModelResult<PageResult<Object[]>> findPageInvestObjectEntity(InvestObjectVO vo) {
		ModelResult<PageResult<Object[]>> result = new ModelResult<PageResult<Object[]>>();
		try {
			result.setModel(investObjectManager.findPageInvestObjectEntity(vo));
		} catch (Exception e) {
			e.printStackTrace();
			result.withError("标的分页查询：", e.getMessage());
		}
		return result;
	}

	@Override
	public ModelResult<String> addInvestObjectEntity(InvestObjectEntity investObjectEntity,
			InvestObjExtEntity investObjExtEntity) {
		ModelResult<String> result = new ModelResult<String>();
		try {
			result.setModel(investObjectManager.addInvestObjectEntity(investObjectEntity));
			investObjExtEntity.setObjectId(result.getModel());
			investObjectExtManager.addInvestObjectExt(investObjExtEntity);
		} catch (Exception e) {
			e.printStackTrace();
			result.withError("标的添加：", e.getMessage());
		}
		return result;
	}

	@Override
	public ModelResult<Boolean> updateInvestObjectEntity(InvestObjectEntity investObjectEntity,
			InvestObjExtEntity investObjExtEntity) {

		ModelResult<Boolean> result = new ModelResult<Boolean>();
		try {
			result.setModel(investObjectManager.updateInvestObjectEntity(investObjectEntity));
			investObjExtEntity.setObjectId(investObjectEntity.getId());
			InvestObjExtEntity ext = investObjectExtManager.findInvestObjExtEntityDetail(investObjectEntity.getId());
			if (ext == null) {
				investObjectExtManager.addInvestObjectExt(investObjExtEntity);
			} else {
				investObjectExtManager.updateInvestObjectExt(investObjExtEntity);

			}
		} catch (Exception e) {
			e.printStackTrace();
			result.withError("标的更新：", e.getMessage());
		}
		return result;

	}

	@Override
	public ModelResult<Boolean> deleteInvestObjectEntity(String id) {

		ModelResult<Boolean> result = new ModelResult<Boolean>();
		try {
			result.setModel(investObjectManager.deleteInvestObjectEntity(id));
		} catch (Exception e) {
			e.printStackTrace();
			result.withError("标的删除：", e.getMessage());
		}
		return result;

	}

	@Override
	public ModelResult<PageResult<InvestObjectEntity>> findFontPageInvestObjectEntity(InvestObjectVO vo) {
		ModelResult<PageResult<InvestObjectEntity>> result = new ModelResult<PageResult<InvestObjectEntity>>();
		try {
			result.setModel(investObjectManager.findFontPageInvestObjectEntity(vo));
		} catch (Exception e) {
			e.printStackTrace();
			result.withError("标的前台分页查询：", e.getMessage());
		}
		return result;

	}

	@Override
	public ModelResult<InvestObjectEntity> findInvestObjectDetail(String id) {

		ModelResult<InvestObjectEntity> result = new ModelResult<InvestObjectEntity>();
		try {
			result.setModel(investObjectManager.findInvestObjectDetail(id));
		} catch (Exception e) {
			e.printStackTrace();
			result.withError("标的详情查询：", e.getMessage());
		}
		return result;

	}

	@Override
	public ModelResult<Boolean> verifyBid(String id, int status,String operator) {
		ModelResult<Boolean> result = new ModelResult<Boolean>();
		try {
			if (status == 10) {// 终止投标
				// 1.首先要把钱划归到投资用户账户里面，成功后进行第2,3步操作
				// 2.更新标的表字段
				result.setModel(investObjectManager.verifyBid(id, status, operator));
				// 3.更新投资记录表字段
				investRecordManager.updateRecordStatus(id);
			} else {
				result.setModel(investObjectManager.verifyBid(id, status,operator));

			}
		} catch (Exception e) {
			e.printStackTrace();
			result.withError("标的审核：", e.getMessage());
		}
		return result;

	}

	@Override
	public ModelResult<InvestObjectVO> getNotVerifyNum(InvestObjectVO vo) {

		ModelResult<InvestObjectVO> result = new ModelResult<InvestObjectVO>();
		try {
			result.setModel(investObjectManager.getNotVerifyNum(vo));
		} catch (Exception e) {
			e.printStackTrace();
			result.withError("标的查询未审核的人数和借款金额：", e.getMessage());
		}
		return result;

	}

	@Override
	public ModelResult<Boolean> addRefundPlan(InvestObjectEntity investObjectEntity) {

		ModelResult<Boolean> model = new ModelResult<Boolean>();
		LoaneeRefundPlanEntity loaneeRefundPlanEntity;
		if (investObjectEntity.getRefundType() == 1) {// 一次性本息

			// 应还款时间=（开始时间+期限）
			Date must_refund_time = null;
			Date onlineTime = investObjectEntity.getLoanTime();// 放款时间
			// 利息=(本金*期限*利率)
			BigDecimal interest = null;
			BigDecimal loanAmount = investObjectEntity.getLoanAmount();// 本金
			BigDecimal annualizedYield = investObjectEntity.getAnnualizedYield();// 年化利率
			BigDecimal deadline = new BigDecimal(investObjectEntity.getDeadline());// 期限
			// 借款类型
			int timeType = 0;
			int interestType = 0;
			int weishu = 10;
			if (investObjectEntity.getDeadlineType() == 0) {
				timeType = Calendar.DATE;
				interestType = 365;
			} else if (investObjectEntity.getDeadlineType() == 1) {
				timeType = Calendar.MONTH;
				interestType = 12;
			}
			// 应还款时间
			if (onlineTime != null) {
				must_refund_time = DateUtils.add(onlineTime, timeType, investObjectEntity.getDeadline());
			}
			// 利息
			interest = loanAmount.multiply(deadline)
					.multiply(annualizedYield.divide(new BigDecimal(interestType), weishu, BigDecimal.ROUND_UP));

			// 插入数据
			loaneeRefundPlanEntity = new LoaneeRefundPlanEntity();
			loaneeRefundPlanEntity.setObjectId(investObjectEntity.getId());
			loaneeRefundPlanEntity.setIssue(1);
			loaneeRefundPlanEntity.setTotalIssues(1);
			loaneeRefundPlanEntity.setRefundType(1);
			loaneeRefundPlanEntity.setLoanee(investObjectEntity.getLoaneeId());
			loaneeRefundPlanEntity.setMustRefundPrincipal(loanAmount);
			loaneeRefundPlanEntity.setMustRefundInterest(interest);
			loaneeRefundPlanEntity.setMustRefundTotal(loanAmount.add(interest));
			loaneeRefundPlanEntity.setMustRefundTime(must_refund_time);
			loaneeRefundPlanEntity.setIsOverdue(0);
			loaneeRefundPlanEntity.setRefundStatus(0);
			loaneeRefundPlanEntity.setCreateTime(new Date());

			try {
				model.setModel(investObjectManager.addRefundPlan(loaneeRefundPlanEntity));
			} catch (Exception e) {
				e.printStackTrace();
				model.withError("新增还款信息失败", e.getMessage());
			}

		} else if (investObjectEntity.getRefundType() == 2) {// 按月付息到期还款

			// 应还款时间=（开始时间+期限）
			Date must_refund_time = null;
			Date onlineTime = investObjectEntity.getLoanTime();// 放款时间
			// 利息=(本金*期限*利率)
			BigDecimal interest = null;
			BigDecimal loanAmount = investObjectEntity.getLoanAmount();// 本金
			BigDecimal annualizedYield = investObjectEntity.getAnnualizedYield();// 年化利率
			int term = 0;// 还款期数

			int timeType = 0;// 时间类型（月，天）
			int interestType = 0;// 利息计算类型（月，天）
			int weishu = 10;// 除法保留位数
			ArrayList<BigDecimal> termList = new ArrayList<>();// 每期的利息

			if (investObjectEntity.getDeadlineType() == 0) {// 按天
				timeType = Calendar.DATE;
				interestType = 365;
				term = investObjectEntity.getDeadline() % 30 > 0 ? ((investObjectEntity.getDeadline() / 30) + 1)
						: (investObjectEntity.getDeadline() / 30);
				if (term == 1) {
					interest = loanAmount.multiply(new BigDecimal(investObjectEntity.getDeadline())).multiply(
							annualizedYield.divide(new BigDecimal(interestType), weishu, BigDecimal.ROUND_UP));
					termList.add(interest);
				} else if (term > 1) {
					for (int i = 1; i < term; i++) {
						interest = loanAmount.multiply(new BigDecimal(30)).multiply(
								annualizedYield.divide(new BigDecimal(interestType), weishu, BigDecimal.ROUND_UP));
						termList.add(interest);
					}
					interest = loanAmount.multiply(new BigDecimal(investObjectEntity.getDeadline() % 30)).multiply(
							annualizedYield.divide(new BigDecimal(interestType), weishu, BigDecimal.ROUND_UP));
					termList.add(interest);
				}
			} else if (investObjectEntity.getDeadlineType() == 1) {// 按月
				timeType = Calendar.MONTH;
				interestType = 12;
				term = investObjectEntity.getDeadline();
				interest = loanAmount
						.multiply(annualizedYield.divide(new BigDecimal(interestType), weishu, BigDecimal.ROUND_UP));
				for (int i = 1; i < term; i++) {
					termList.add(interest);
				}
			}
			if (onlineTime != null) {
				must_refund_time = DateUtils.add(onlineTime, timeType, investObjectEntity.getDeadline());
			}

			if (termList.size() == 1) {
				loaneeRefundPlanEntity = new LoaneeRefundPlanEntity();
				loaneeRefundPlanEntity.setObjectId(investObjectEntity.getId());
				loaneeRefundPlanEntity.setIsOverdue(0);
				loaneeRefundPlanEntity.setRefundStatus(0);
				loaneeRefundPlanEntity.setCreateTime(new Date());
				loaneeRefundPlanEntity.setLoanee(investObjectEntity.getLoaneeId());

				loaneeRefundPlanEntity.setIssue(1);
				loaneeRefundPlanEntity.setTotalIssues(termList.size());
				loaneeRefundPlanEntity.setRefundType(2);
				loaneeRefundPlanEntity.setMustRefundPrincipal(investObjectEntity.getLoanAmount());
				loaneeRefundPlanEntity.setMustRefundInterest(interest);
				loaneeRefundPlanEntity.setMustRefundTotal(investObjectEntity.getLoanAmount().add(interest));
				loaneeRefundPlanEntity.setMustRefundTime(must_refund_time);
				try {
					model.setModel(investObjectManager.addRefundPlan(loaneeRefundPlanEntity));
				} catch (Exception e) {
					e.printStackTrace();
					model.withError("新增还款信息失败", e.getMessage());
				}
			} else if (termList.size() > 1) {
				for (int i = 1; i < termList.size(); i++) {
					loaneeRefundPlanEntity = new LoaneeRefundPlanEntity();
					loaneeRefundPlanEntity.setObjectId(investObjectEntity.getId());
					loaneeRefundPlanEntity.setIsOverdue(0);
					loaneeRefundPlanEntity.setRefundStatus(0);
					loaneeRefundPlanEntity.setCreateTime(new Date());
					loaneeRefundPlanEntity.setLoanee(investObjectEntity.getLoaneeId());

					loaneeRefundPlanEntity.setIssue(i);
					loaneeRefundPlanEntity.setTotalIssues(termList.size());
					loaneeRefundPlanEntity.setRefundType(2);
					loaneeRefundPlanEntity.setMustRefundPrincipal(new BigDecimal(0));
					loaneeRefundPlanEntity.setMustRefundInterest(termList.get(i - 1));
					loaneeRefundPlanEntity.setMustRefundTotal(termList.get(i - 1));
					loaneeRefundPlanEntity.setMustRefundTime(must_refund_time);
					try {
						model.setModel(investObjectManager.addRefundPlan(loaneeRefundPlanEntity));
					} catch (Exception e) {
						e.printStackTrace();
						model.withError("新增还款信息失败", e.getMessage());
					}
				}

				LoaneeRefundPlanEntity loaneeRefundPlanEntity1 = new LoaneeRefundPlanEntity();
				loaneeRefundPlanEntity1.setObjectId(investObjectEntity.getId());
				loaneeRefundPlanEntity1.setIsOverdue(0);
				loaneeRefundPlanEntity1.setRefundStatus(0);
				loaneeRefundPlanEntity1.setCreateTime(new Date());
				loaneeRefundPlanEntity1.setLoanee(investObjectEntity.getLoaneeId());

				loaneeRefundPlanEntity1.setIssue(termList.size());
				loaneeRefundPlanEntity1.setTotalIssues(termList.size());
				loaneeRefundPlanEntity1.setRefundType(2);
				loaneeRefundPlanEntity1.setMustRefundPrincipal(investObjectEntity.getLoanAmount());
				loaneeRefundPlanEntity1.setMustRefundInterest(termList.get(termList.size() - 1));
				loaneeRefundPlanEntity1.setMustRefundTotal(loanAmount.add(termList.get(termList.size() - 1)));
				loaneeRefundPlanEntity1.setMustRefundTime(must_refund_time);
				try {
					model.setModel(investObjectManager.addRefundPlan(loaneeRefundPlanEntity1));
				} catch (Exception e) {
					e.printStackTrace();
					model.withError("新增还款信息失败", e.getMessage());
				}
			}

		}

		return model;
	}

	@Override
	public ModelResult<InvestObjExtEntity> findInvestObjExtEntityDetail(String bid) {
		ModelResult<InvestObjExtEntity> result = new ModelResult<InvestObjExtEntity>();
		try {
			result.setModel(investObjectExtManager.findInvestObjExtEntityDetail(bid));
		} catch (Exception e) {
			e.printStackTrace();
			result.withError("标的扩展详情查询：", e.getMessage());
		}
		return result;
	}

	@Override
	public ModelResult<Boolean> addInvestorIncomeDetail(String id) {
		ModelResult<Boolean> result = new ModelResult<Boolean>();
		InvestorRecordEntity entity = new InvestorRecordEntity();
		entity.setObjectId(id);
		entity.setStatus(1);
		List<InvestorRecordEntity> list = investorDao.queryInvestorRecordList(entity);// 查询该标的的投资用户
		InvestObjectEntity object = investObjectManager.findInvestObjectDetail(id);// 根据id查询标的信息
		if (object.getRefundType() == 1) {// 一次性还款

			for (InvestorRecordEntity record : list) {
				InvestorIncomeDetailEntity incomeEntity = new InvestorIncomeDetailEntity();
				incomeEntity.setObjectId(id);
				incomeEntity.setInvestId(record.getInvestorId());
				incomeEntity.setIssue(1);
				incomeEntity.setPrincipal(record.getInvestAmount());
				incomeEntity.setIncome(record.getExpectAmount());
				incomeEntity.setStatus(0);
				investorIncomeDetailManager.add(incomeEntity);
			}

		} else {

			int term = 0;
            int lastTerm=0;//最后一期多少天
            BigDecimal fullnum=new BigDecimal(0);//满月占的%
            BigDecimal num=new BigDecimal(0);//满月占的%
			if (object.getDeadlineType() == 0) {// 按天
				term = object.getDeadline() % 30 > 0 ? ((object.getDeadline() / 30) + 1) : (object.getDeadline() / 30);
				lastTerm=object.getDeadline() % 30 ;
				fullnum=new BigDecimal(30).divide(new BigDecimal(object.getDeadline()),4,BigDecimal.ROUND_HALF_DOWN);
				num=new BigDecimal(lastTerm).divide(new BigDecimal(object.getDeadline()),4,BigDecimal.ROUND_HALF_DOWN);
			} else if (object.getDeadlineType() == 1) {// 按月

				term = object.getDeadline();

			}

			for (int i = 0; i < term; i++) {
				for (InvestorRecordEntity record : list) {
					InvestorIncomeDetailEntity incomeEntity = new InvestorIncomeDetailEntity();
					incomeEntity.setObjectId(id);
					incomeEntity.setInvestId(record.getInvestorId());
					incomeEntity.setIssue(i + 1);
					incomeEntity.setPrincipal(record.getInvestAmount());
					if (object.getDeadlineType() == 1 || lastTerm == 0) {// 按月或者按天正好是一个月
						incomeEntity.setIncome(record.getExpectAmount().divide(new BigDecimal(term),4,BigDecimal.ROUND_HALF_DOWN));
					}else{
						 if(i<term-1){
							 incomeEntity.setIncome(record.getExpectAmount().multiply(fullnum).setScale(4,RoundingMode.HALF_DOWN));
						 }else{
							 incomeEntity.setIncome(record.getExpectAmount().multiply(num).setScale(4,RoundingMode.HALF_DOWN));
						 }
					}
					incomeEntity.setStatus(0);
					investorIncomeDetailManager.add(incomeEntity);
				}

			}

		}

		return result;
	}
	


}
